/**
 * 
 */
package leilib.ir.crawler.pages;

import java.util.ArrayList;

/**
 * @author LeilibPC
 * 
 */
public class PagesQueue<E> {
	ArrayList<E> buffer = new ArrayList<E>();
	private int maxSize = 1;
	private Object locker = new Object();

	public PagesQueue(int bufferSize) {
		this.maxSize = bufferSize;
	}

	public E take(long timeout) {
		synchronized (locker) {
			try {
				this.locker.wait(timeout);

				if (this.isEmpty()) {
					locker.notify();
					return null;
				} else {
					E e = this.buffer.remove(0);
					locker.notify();

					return e;
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
				return null;
			}

		}
	}

	public boolean put(E e) {
		synchronized (locker) {
			while (this.isFull()) {
				try {
					this.locker.wait();
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
			}

			boolean flag = this.buffer.add(e);
			this.locker.notify();

			return flag;

		}
	}

	private boolean isEmpty() {
		synchronized (this.locker) {
			if (this.buffer.size() == 0) {
				return true;
			} else {
				return false;
			}
		}
	}

	private boolean isFull() {
		synchronized (this.locker) {
			if (this.buffer.size() >= this.maxSize) {
				return true;
			} else {
				return false;
			}
		}
	}

	public int size() {
		return this.buffer.size();
	}
}
